package com.xin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.annoations.Permission;
import com.xin.entity.crm.PermissionEntity;
import com.xin.mapper.PermissionMapper;
import com.xin.service.PermissionService;
import com.xin.utils.reflection.ControllerMethodUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 权限管理
 */
@Service
public class PermissionServiceImpl extends ServiceImpl< PermissionMapper,PermissionEntity> implements PermissionService {


    /**
     * 项目启动先清空权限信息，在添加权限信息
     * @param applicationContext
     * @return
     */
    @Override
    @Transactional
    public Integer addList(ApplicationContext applicationContext) {
        //清空权限信息
        this.clearList();
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            Object bean = applicationContext.getBean(beanDefinitionName);
            Class<?> aClass = bean.getClass();
            Permission annotation = aClass.getAnnotation(Permission.class);
            //判断该bean上面是否含有权限信息，是否添加到数据库
            if (annotation==null) continue;
            PermissionEntity permissionEntity = new PermissionEntity();
            permissionEntity.setSn(annotation.sn());
            permissionEntity.setName(annotation.value());
            //获取控制器的请求路径
            RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class);
            String[] value = requestMapping.value();
            permissionEntity.setUrl(value[0]);
            //保存父权限
            this.save(permissionEntity);
            //获取该类上的所有方法
            Method[] methods = aClass.getDeclaredMethods();
            for (Method method : methods) {
                Permission permission = method.getAnnotation(Permission.class);
                if (permission==null) continue;
                PermissionEntity sons = new PermissionEntity();
                //绑定该权限的父权限
                sons.setParentId(permissionEntity.getId());
                sons.setSn(permission.sn());
                sons.setName(permission.value());
                //获取请求url
                sons.setUrl(permissionEntity.getUrl()+ControllerMethodUtils.getUrl(method));
                //添加到数据库
                this.save(sons);
            }

        }
        return 1;
    }

    /**
     * 清空权限信息
     * @return
     */
    @Override
    public Integer clearList() {
        int delete = this.baseMapper.delete(null);
        return delete;
    }

    @Override
    public Page<PermissionEntity> findAll(Integer page,Integer size) {
        //查询所有权限信息
        List<PermissionEntity> permissionEntities = this.baseMapper.selectList(null);
        Map<Long, PermissionEntity> permissionMap = permissionEntities.stream()
                .collect(Collectors.toMap(item -> item.getId(), item -> item));
        //分页查询
        Page<PermissionEntity> pages = new Page<>(page,size);
        Page<PermissionEntity> permissionEntityPage = this.baseMapper.selectPage(pages, null);

        List<PermissionEntity> records = permissionEntityPage.getRecords();
        for (PermissionEntity record : records) {
            if (record.getParentId()!=null&&record.getParentId().longValue()!=0)
                record.setParentName(permissionMap.get(record.getParentId()).getParentName());
        }

        return permissionEntityPage;

    }

    @Override
    public List<PermissionEntity> findAllByTree() {
        //查询所有权限信息
        List<PermissionEntity> permissionEntities = this.baseMapper.selectList(null);
        //根据权限的id 转换为map
        Map<Long, PermissionEntity> permissionMap = permissionEntities.stream().collect(Collectors.toMap(item -> item.getId(), item -> item));
        //构建树节点
        permissionMap.forEach((key,value)->{
            //如果父权限不为空
            PermissionEntity permissionEntity = permissionMap.get(value.getParentId());
            if (permissionEntity!=null){
                List<PermissionEntity> child = permissionEntity.getChild();
                if (child==null){
                    permissionEntity.setChild(new ArrayList<>());
                }
                permissionEntity.getChild().add(value);
            }
        });
        //返回所有顶级节点
        return permissionMap.values().stream().filter(item->item.getParentId()==null||item.getParentId().longValue()==0).collect(Collectors.toList());
    }
}
